#include "vcl_stl.h"

char *SimbatBase = NULL;

#ifdef BK_AIX
   static string SysName = "aix";
#endif
#ifdef BK_LINUX
   static string SysName = "linux";
#endif
#ifdef BK_HP
   static string SysName = "hp";
#endif
#ifdef BK_SOLARIS
   static string SysName = "solaris";
#endif

static bool System(const char *s);

static bool System(const char *s)
{
   int r;

   printf("executing : %s\n", s);
   r = system(s);

   return WIFEXITED(r) && WEXITSTATUS(r) == 0;
}

static bool MkInstall();

static bool MkInstall()
{
   char Command[2048 + 1];

   chdir(SimbatBase);
   System("simbat_ctl stop");
   System("rm -fr release");

   if ( !System("mkdir release") )
   {
      return false;
   }

   {
      FILE *f = fopen("install/version", "wt");
      if ( f == NULL )
      {
         fprintf(stderr, "Can not create install/version, errno = %d\n", errno);
      }
      fprintf(f, "%s ( %s )\n", VERSION_STRING, EDITION_STRING);
      fprintf(f, "Build time : %s, %s\n", __DATE__, __TIME__);
      fsync(fileno(f));
      fclose(f);
   }

   chdir("release");
   System("mkdir bats bin etc include lib plugin sample tmp");

   System("cp $SIMBAT_BASE/bin/* bin");
   System("mv bin/simbat_install .");
   System("cp $SIMBAT_BASE/install/install.cfg .");
   System("cp $SIMBAT_BASE/install/version .");
   System("rm bin/simbat_mkinstall");
   System("cp $SIMBAT_BASE/install/config_default.xml etc");
   System("cp $SIMBAT_BASE/install/config_cust_default.xml etc");
   System("cp $SIMBAT_BASE/install/auth_default.xml etc");
   System("cp $SIMBAT_BASE/install/var_pool_default etc");
   System("cp $SIMBAT_BASE/install/http_post_default.ini etc");
   System("cp $SIMBAT_BASE/install/version etc");
   System("cp $SIMBAT_BASE/include/simbat_plugin.h include");
   System("cp $SIMBAT_BASE/lib/* lib");
   System("cp $SIMBAT_BASE/sample/* sample");

   if ( SysName == "aix" )
   {
      System("tar -cvf simbat.tar bats bin etc include lib plugin sample tmp");
      System("compress simbat.tar");
   }
   else
   {
      System("zip -r simbat.zip bats bin etc include lib plugin sample tmp");
   }

   System("rm -r bats bin etc include lib plugin sample tmp");
   return true;
}

int main(void)
{
   SimbatBase = getenv("SIMBAT_BASE");

   if ( SimbatBase == NULL )
   {
      fprintf(stderr, "$SIMBAT_BASE not defined\n");
      return 8;
   }

   if ( !MkInstall() )
   {
      return 8;
   }

   return 0;
}
